#include "../src/ObjectArray.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct _TestObject
{
	EventObject parent_instance;
	euint32	    number;
} TestObject;

static TestObject *
test_object_new(euint32 number)
{
	TestObject *object = MALLOC_NEW(TestObject);

	event_object_init(EVENT_OBJECT(object));
	object->number = number;

	return object;
}

static bool
test_object_compare(const TestObject *obj1, const TestObject *obj2)
{
	return_val_if_fail(obj1 != NULL && obj2 != NULL, test_object_compare,
			   false);
	return obj1->number > obj2->number;
}

static void
test_object_print(const TestObject *object)
{
	printf("TestObject<%p>: %u\n", object, object->number);
}

int
main(void)
{
	ObjectArray *array;
	TestObject  *test, *tmp;
	int	     index;

	array = object_array_new(50);
	object_array_set_sort_function(array,
				       (ObjectSortFunc)test_object_compare);
	object_array_set_is_positive_sequence(array, false);
	object_array_set_object_finalize(array, event_object_unref);
	srand(time(NULL));

	for (int i = 0; i < 21; ++i) {
		test = test_object_new((euint32)rand() % 12341223);
		object_array_insert_object(array, test);
		if (i == 10) {
			printf("#debug: 删除第 11 个，number: %u\n",
			       test->number);
			tmp = test;
		}
	}

	object_array_sort(array);
	object_array_iteration_reset(array);

	index = 1;
	test  = (TestObject *)object_array_iteration_get(array);
	while (test) {
		printf("%d: ", index++);
		test_object_print(test);
		test = (TestObject *)object_array_iteration_get(array);
	}

	printf("删除 %u\n", tmp->number);
	object_array_remove_object(array, tmp);
	object_array_sort(array);
	object_array_iteration_reset(array);
	index = 1;
	test  = (TestObject *)object_array_iteration_get(array);
	while (test) {
		printf("%d: ", index++);
		test_object_print(test);
		test = (TestObject *)object_array_iteration_get(array);
	}

	event_object_unref(array);
	return 0;
}
